package service

import (
	"context"
	"fmt"
	"gorm.io/gorm"
	"math/rand"
	"srv/basic/global"
	__ "srv/basic/proto"
	"srv/handler/model"
	"srv/pkg"
	"strconv"
)

type Service struct {
	__.UnimplementedUserServer
}

//学校信息录入

func (s *Service) SchoolAdd(_ context.Context, req *__.SchoolAddReq) (resp *__.SchoolAddResp, err error) {
	school := model.School{}

	global.DB.Debug().Where("name = ?", req.Name).First(&school)

	if school.ID != 0 {
		return nil, fmt.Errorf("school already exists")
	}

	school = model.School{
		Name:      req.Name,
		Status:    1,
		Types:     req.Types,
		Address:   req.Address,
		Tel:       req.Tel,
		Introduce: req.Introduce,
		CoverUrl:  req.CoverUrl,
	}

	err = global.DB.Debug().Create(&school).Error
	if err != nil {
		return nil, err
	}
	resp = &__.SchoolAddResp{
		Id:   int64(school.ID),
		Name: school.Name,
	}

	return resp, nil
}

func (s *Service) AccountAdd(_ context.Context, req *__.AccountAddReq) (resp *__.AccountAddResp, err error) {

	admin := model.Admin{}

	global.DB.Debug().Where("username = ?", req.Username).First(&admin)

	if admin.ID != 0 {
		return nil, fmt.Errorf("admin already exists")
	}

	password := strconv.Itoa(rand.Intn(900000) + 100000)
	admin = model.Admin{
		Username: req.Username,
		Password: password,
		Mobile:   req.Mobile,
		SchoolId: req.SchoolId,
		Role:     2,
	}

	err = global.DB.Debug().Create(&admin).Error
	if err != nil {
		return nil, err
	}

	//  发送短信
	sms, err := pkg.SendSms(admin.Mobile, password)
	if err != nil {
		return nil, fmt.Errorf("短信发送失败:%s", err)
	} else if sms != nil && *sms.Body.Code == "OK" {
		fmt.Printf("短信发送成功，新账号密码: %s\n", password)
	}

	resp = &__.AccountAddResp{
		Id:       int64(admin.ID),
		Username: admin.Username,
	}

	return resp, nil

}

func (s *Service) SchoolList(_ context.Context, req *__.SchoolListReq) (resp *__.SchoolListResp, err error) {

	var schools []model.School

	tx := global.DB.Model(&model.School{})

	if req.Name != "" {
		tx = tx.Where("name = ?", req.Name)
	}

	if req.Status != 0 {
		tx = tx.Where("status = ?", req.Status)
	}

	tx.Scopes(Paginate(int(req.Page))).Order("created_at desc").Find(&schools)

	// 遍历转换成响应结构
	var schoolList []*__.SchoolList

	for _, school := range schools {
		list := &__.SchoolList{
			Name:     school.Name,
			Types:    school.Types,
			Tel:      school.Tel,
			Address:  school.Address,
			CoverUrl: school.CoverUrl,
			Status:   int64(school.Status),
		}
		schoolList = append(schoolList, list)
	}

	resp = &__.SchoolListResp{
		List: schoolList,
	}

	return resp, nil

}
func Paginate(page int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {

		if page <= 0 {
			page = 1
		}

		pageSize := 20 // 固定每页显示 20 条

		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}

//  账号管理与查询功能

func (s *Service) UserList(_ context.Context, req *__.UserListReq) (resp *__.UserListResp, err error) {

	var admins []model.AdminSchool

	tx := global.DB.Debug().Model(&model.Admin{}).
		Select("admins.*,schools.name as name").
		Joins("left join schools on schools.id = admins.school_id")

	if req.Mobile != "" {
		tx = tx.Where("mobile = ?", req.Mobile)
	}

	tx.Find(&admins)

	// 遍历转换成响应结构
	var userList []*__.UserList

	for _, admin := range admins {
		list := &__.UserList{
			Username:   admin.Username,
			Schoolname: admin.Name,
			Mobile:     admin.Mobile,
		}
		userList = append(userList, list)
	}

	resp = &__.UserListResp{
		List: userList,
	}

	return resp, nil

}
